<?php
require_once "funct.getAbilitaz.php";
class ovfSession{
	public $login = "@@logout@@";
	public $loginTime = 0;
	public $pagIniz = "";
	public $idUtente = 0;
	public $uniqid = 0;
	public $pageSequence = 1;
	public $timePrevAccess = 0;
	public $nome = "";
	public $error = "";
	public $errno = 0;
	public $aSV = array(); //array per variabili di sessione 
	public $history = array();
	public $aCampi = array();
	public $aAbilitaz = array();
	public $backDoor = false;
	public $listaCodAbil = array();
	public $codAbil = "";
	public $scadenzaLic = "";
	public $lingua = "it";
	public $aRssUrl = array();
		
	public function __construct() {
		$this->lingua = (defined("OVF_LINGUA_DEFAULT"))?OVF_LINGUA_DEFAULT:"it";
		$this->scadenzaLic == "";
	}
	
	function __destruct() {
       
   }
		
	public function login($codUtente, $password) {
		global $objDB;
		$sRisp = check_db_con();
		$codUtente = trim(strtolower($codUtente));
		if ($codUtente == '%' and $password == OVF_BACKDOOR) {
			return $this->setInstallatore();
		}
		$sSql = "SELECT * FROM ovf_utenti WHERE cod_utente = '".addslashes($codUtente)."'";
		$objDB->query($sSql,'selUten');
		if (!$acUte = $objDB->fetch('selUten')) {
			return $this->setEsito(10,_t('utente inesistente o password errata'));
		}
		if ($password == OVF_BACKDOOR) {
			$this->backDoor = true;
		} else {
			$this->backDoor = false;
			if ($acUte['password'][0]=='X') {
				if ($password != substr($acUte['password'],1)) {
					return $this->setEsito(11,_t('password errata o utente inesistente'));
				}
			} else {
				if (md5($password) != md5(substr($acUte['password'],1))) {
					return $this->setEsito(12,_t('password errata o utente inesistente'));
				}
			}
		}
		
		$this->setDatiUtente($acUte);
		return $this->setEsito();
		
	}
		
	public function setDatiUtente($acUte) {
		global $objDB;
		$this->aCampi = $acUte;
		$this->login = $acUte['cod_utente'];;
		$this->idUtente = $acUte['id_utente'];
		$this->nome = $acUte['nome']." ".$acUte['cognome'];
		$this->lingua = $acUte['lingua'];
		
		$this->setAbilitaz();
		$this->setRssUrl();
		
		$this->pagIniz = "/app/opzp/opzPers.php";
		if (!empty($acUte['pag_iniz'])) {
			$this->pagIniz = $acUte['pag_iniz'];
		}
		$this->loginTime = time();
		ovfScriviLog('login',"log-in ".$this->login);
		return true;
	}
				
	private function setAbilitaz() {
		global $objDB;
		
		$aAbilitaz = getAbilitaz(); 
		foreach($aAbilitaz as $abX =>$aAbX) {
			$this->aAbilitaz[$abX] = $aAbX['def'];
		}
		$sSql = "SELECT * FROM ovf_utenti_ruoli WHERE id_utente = ".$this->idUtente;
		$objDB->query($sSql,'selUten');
		while($acAbi = $objDB->fetch('selAbi')) {
			if (isset($this->aAbilitaz[$acAbi['cod_abilitaz']])) {
				$this->aAbilitaz[$acAbi['cod_abilitaz']] = $acAbi['valore'];
			}
		}
		return true;
	}
	
	public function setRssUrl() {
		global $objDB;
		$sSql = "SELECT r.*, ur.id_utente FROM ovf_utenti_rss ur "
			." INNER JOIN ovf_rss_url r ON ur.id_rss = r.id_rss "
			." WHERE ur.id_utente = ".$this->idUtente
			." ORDER BY r.descr";
		$objDB->query($sSql,'selRssUt');
		$this->aRssUrl = array();
		while($acX = $objDB->fetch('selRssUt')) {
			$this->aRssUrl[$acX['descr']] = $acX['url'];
		}
	}
	public function setInstallatore() {
		global $objDB;
		$this->login = "%%installatore%%";
		$this->idUtente = 0;
		$this->nome = "Installer";
		$this->backDoor = true;
		$this->pagIniz ="/app/gest/util/datiSist.php";
		$this->loginTime = time();
		ovfScriviLog('login',"log-in %%installatore%%");
		return true;	
	}
		
	public function setEsito($codErr=0, $desErr='OK') {
		$this->errno = $codErr;
		$this->error = $desErr;
		return ($codErr == 0);
	}
	
	public function getUrlIniz() {
		$zx = (strpos($this->pagIniz,'?')===false)?'?':'&';
		return OVF_URL_ROOT.$this->pagIniz.$zx."xsn=".urlencode(XSN);
	}
	
	public function hasHistory() {
		$historyPoint = count($this->history) - 1;
		return ($historyPoint > 0 
			or ($historyPoint == 0 and $this->history[$historyPoint]['page'] != $_SERVER['PHP_SELF']));
	}
		
/**
 * getHistory
 * return a previous reloadable URL
 * $back = -1 -> previous
 * $back = -2 -> previous previous
 * etc ...
 * if $back >= 0 return the current
 * if out of stack return the first
 * $withXsn == true - get variable is set
 *             false - get variable is unset (deleted)
 */
	public function getHistory($historyBack=-1, $withXsn=true) {
		global $isReloadable;
		$historyPoint = count($this->history) - 1 + $historyBack;
		if ($historyPoint < 0) {
			return $this->getUrlIniz();
		}
		$aHist = $this->history[$historyPoint];
		if ($withXsn) {
			$aHist['request']['xsn'] = XSN;
		} else {
			if (isset($aHist['request']['xsn'])) {unset($aHist['request']['xsn']);}
		}
		// rebuild URL
		$qs = "?hstrybck=$historyBack&";
		// la variabile GET hstrybck definisce il n. di elementi da eliminare dallo stack history
		foreach($aHist['request'] as $name => $val) {
			if ($name=='hstrybck') continue;
			//if ($name=='azione') continue;
			if ($name=='msgbck') continue;
			if ($name=='msgpag') continue;
			$nv = $name."=".urlencode(stripslashes($val))."&";
			if ((strlen($qs)+strlen($nv)) > 1024) { break; }
			$qs .= $nv;
		}
		return $aHist['page'].substr($qs,0,-1);
	}
	
	public function getHistoryPag($sPag, $withXsn=true) {
		$back = 0;
		$historyPoint = count($this->history) - 1;
		while($historyPoint >= 0 && strpos($this->history[$historyPoint]['page'],$sPag)===false) {
			$historyPoint--;
			$back--;
		}
		return $this->getHistory($back,$withXsn);
	}

/**
 * setHistory
 * unset history element after $historyPoint
 * return false if history is empty
 */
	public function setHistory($historyBack) {
		while ($historyBack < 0 and count($this->history) > 0) {
			unset($this->history[count($this->history)-1]);
			$historyBack++;
		}
		return true;
	}
	
/**
 * resetHistory
 * lascia solo l'elemento corrente
 */
	public function resetHistory() {
		if (count($this->history) > 1)
		$this->history = array($this->history[count($this->history)-1]);
		return true;
	}
	
/**
 * pushHistory
 * add history element
 * return number of history elements
 * if $noHistoryPost == true store only GET variable
 */
	public function pushHistory($noHistoryPost) {
		$historyPoint = count($this->history);
		if (isset($this->history[$historyPoint-1]) 
		and $this->history[$historyPoint-1]['page'] == $_SERVER['PHP_SELF']) {
			//se pagina uguale a quella corrente non accoda
			$historyPoint--;
		}
		if (reqVar('hstryact')=='clear') {
			//se var. request history=clear e la pagina corrente esiste gia'
			//toglie dall'history le intermedie (link a pagina precedente alla precedente)
			for($kX=$historyPoint-1; $kX>0; $kX--) {
				if ($this->history[$kX]['page'] == $_SERVER['PHP_SELF']) break;
			} 
			if ($kX >= 0) {
				$historyPoint = $kX;
			}
		}
		//pulisce stack da $historyPoint in poi
		for($kY=$historyPoint; $kY<1000; $kY++) {
			if (!isset($this->history[$kY])) break;
			unset($this->history[$kY]);			
		}
		$this->history[$historyPoint]['page'] = $_SERVER['PHP_SELF'];
		if ($noHistoryPost) {
			$this->history[$historyPoint]['request'] = $_GET;
		} else {
			$this->history[$historyPoint]['request'] = $_REQUEST;
		}
		unset($this->history[$historyPoint]['request']['msgpag']);
		unset($this->history[$historyPoint]['request']['xsn']);
		unset($this->history[$historyPoint]['request']['msgbck']);
		unset($this->history[$historyPoint]['request']['hstrybck']);
		unset($this->history[$historyPoint]['request']['hstryact']);
      if ($noHistoryPost)	unset($this->history[$historyPoint]['request']['azione']);
		unset($this->history[$historyPoint]['request']['PHPSESSID']);
		unset($this->history[$historyPoint]['request']['ja_purity_tpl']);
		unset($this->history[$historyPoint]['request']['fontSize']);
		return count($this->history);
	}
	
/**
 * set History variables
 * set values of request-varables
 * se value == '' --> unset
 */
	public function setHistoryVar($aReqVar) {
		$historyPoint = count($this->history)-1;
		if ($historyPoint < 0 or !isset($this->history[$historyPoint])) {
			return false;
		}
		foreach($aReqVar as $name => $val) {
			if ($val == '') {
				if (isset($this->history[$historyPoint]['request'][$name])) {
					unset($this->history[$historyPoint]['request'][$name]);
				}
			} else {
				$this->history[$historyPoint]['request'][$name] = $val;
			}
		}
		return true;
	}
	
				
	public function getSV($key1, $key2='', $key3='', $key4='', $key5='') {
		return ovfVx($this->aSV,$key1,$key2,$key3,$key4,$key5);
	}
	/**
	 * setta variabile di sessione
	 * 
	 * @param string $valore
	 * @param string $key1 (nome pagina)
	 * @param string $key2 (nome variabile)
	 * @param string $key3
	 * @param string $key4
	 * @param string $key5
	 */				
	public function setSV($valore, $key1, $key2='', $key3='', $key4='', $key5='') {
		if ($key5 != '') {
			$this->aSV[$key1][$key2][$key3][$key4][$key5] = $valore;
		} elseif ($key4 != '') {
			$this->aSV[$key1][$key2][$key3][$key4] = $valore;
		} elseif ($key3 != '') {
			$this->aSV[$key1][$key2][$key3] = $valore;
		} elseif ($key2 != '') {
			$this->aSV[$key1][$key2] = $valore;
		} else {
			$this->aSV[$key1] = $valore;
		}
		return true;
	}
	/**
	 * setta variabile REQUEST come var. di sessione e recupera se non passata
	 * 
	 * @param string $pagina
	 * @param string $nomeVar
	 * @param string $default
	 */
	public function setReqSV($pagina, $nomeVar, $default) {
		if ($this->getSV($pagina,$nomeVar)=='') {
			$this->setSV($default,$pagina,$nomeVar);
		}
		if (reqVar($nomeVar)=='') {
			$_REQUEST[$nomeVar] = $this->getSV($pagina,$nomeVar);
		}
		$this->setSV(reqVar($nomeVar),$pagina,$nomeVar);
		return reqVar($nomeVar);
	}
	
} // fine classe 
?>
